import Log from '@src/util/log'

const DICT = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
const CapitalLetterReg = /[A-Z]/g

/** 生成随机字符串 */
export function randomString(length = 8) {
  let chars: string[] = [];
  
  for (let i = 0; i < length; i++) {
    chars.push(DICT[Math.floor(Math.random() * DICT.length)])
  }
  
  return chars.join('');
}

/**
 * @description: 获取唯一id
 * ! 伪唯一id
 * @return {String} 唯一id
 */
export function uuid() {
  let uuidString = ''
  
  try {
    const HexDigits = '0123456789abcdef'
    let s: string[] = [];
    
    for (let i = 0; i < 36; i++) {
      s[i] = HexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    
    // bits 12-15 of the time_hi_and_version field to 0010
    s[14] = '4'
    // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[19] = HexDigits.substr((Number(s[19]) & 0x3) | 0x8, 1)
    s[8] = s[13] = s[18] = s[23] = '-'
    
    uuidString = s.join('')
    
  } catch (error) {
    uuidString = String(Math.random() * 10000 >> 2)
    Log.error(error, uuid.name)
  }

  return uuidString
}

/**
 * @description: 计算字符串字节长度
 * -- 汉字按两个字节，英文字母按一个字节
 * @param {string} str 需要计算的字符串
 * @return {Number} 字符串的字节长度
 */
export function computedStrLen(str: string): number {
  let len = 0

  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    // 单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++
    } else {
      len += 2
    }
  }

  return len
}

/**
 * @description: 连接接字符串数组
 * @param {String[]} strings 字符串数组
 * @param {String} separator 分隔符
 * !! separator 的默认值为 ',' 英文逗号，千万不要修改默认值，否则会影响到工单导出的代码
 * @return {String} 连接后的字符串
 */
export function concat(strings: string[], separator: string = ','): string {
  try {
    return strings.join(separator)
  } catch (error) {
    Log.error(error, concat.name)
    return ''
  }
}

export function camelToUnderline(camelStr: string): string {
	return (
    camelStr
      .replace(
        CapitalLetterReg, 
        function(str){
          return ' '+ str.toLowerCase()
        }
      )
      .trim()
      .replaceAll(' ','_')
  )
}

export default {
  uuid,
  computedStrLen,
  concat
}